from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from config import Config
import os
from app.models.db_setup import db
from app.utils.wx_token_manager import token_manager

# 创建扩展实例
jwt = JWTManager()


def create_app():
    # 创建Flask应用
    app = Flask(__name__)
    app.config.from_object(Config)

    # 确保上传目录存在
    upload_folder = app.config.get("UPLOAD_FOLDER", "uploads")
    if not os.path.exists(upload_folder):
        os.makedirs(upload_folder)

    # 初始化扩展
    db.init_app(app)
    jwt.init_app(app)
    CORS(app)

    # 初始化微信Token管理器
    token_manager.init_app(app)

    # 导入模型 - 必须在db初始化后导入
    with app.app_context():
        from app.models import user, product, cart, order  # 仅导入模块，不直接使用类

    # 导入和注册蓝图
    from app.routes.user import user_bp
    from app.routes.product import product_bp
    from app.routes.cart import cart_bp
    from app.routes.order import order_bp

    app.register_blueprint(user_bp, url_prefix="/api/user")
    app.register_blueprint(product_bp, url_prefix="/api/products")
    app.register_blueprint(cart_bp, url_prefix="/api/cart")
    app.register_blueprint(order_bp, url_prefix="/api/orders")

    # 创建数据库表
    with app.app_context():
        db.create_all()

    @app.before_first_request
    def initialize_app():
        # 应用启动后的初始化操作
        pass

    return app


# 针对直接运行
if __name__ == "__main__":
    app = create_app()
    app.run(host="0.0.0.0", port=5000, debug=True)
